import { useEffect, useState, Fragment } from 'react'
import { connect } from 'react-redux'
import Login from '../../components/login'
import Register from '../../components/register'

import {
	wrapper,
	back,
	main,
	title,
	tips,
	button,
} from './index.module.css'

function Home(props) {
	const { islogin } = props;


	const [showLog, setShowLog] = useState(false);
	const [showReg, setShowReg] = useState(false);


	useEffect(() =>{
		if (props.location.state) {
			const {log} = props.location.state;
			if (log && !islogin) {
				setShowLog(true);
			} 
		}
	}, [props.location.state, islogin])
	function showLogin() {
		// 登录后点击直接进入room页
		if (islogin) {
			props.history.push({pathname: `/room`});
			return;
		}
		setShowLog(true);
	}
	function closeLogin() {
		setShowLog(false);
	}
	function showRegister(e) {
		e.preventDefault();
		setShowReg(true);
		closeLogin();
	}
	function closeRegister() {
		setShowReg(false);
	}

	
	return (
		<Fragment>
			<div className={wrapper}>
				<div className={back}></div>
				<div className={main}>
					<h2 className={title}>一个聊天室</h2>
					<p className={tips}>暂时就说这么多</p>
					<button className={button} onClick={showLogin}>开始</button>
				</div>
			</div>
			<Login 
				show={showLog} 
				closeLogPopup={closeLogin} 
				showRegPopup={showRegister} 
				logIn={()=>{props.history.push({pathname: '/room'})}} 
			/>
			<Register show={showReg} closeRegPopup={closeRegister} />
		</Fragment>
	);
}

function mapStateToProps(state) {
	return {
		islogin: state.islogin,
	}
}
export default connect(
	mapStateToProps,
	{}
)(Home);
